package Service.Teacher.Imp;

import Dao.DaoFactory;
import Dao.Role.StuInfoDao;
import Dao.Role.TeacherDao;
import Dao.TitleAndPaper.TitleDao;
import Entity.MyTableData;
import Entity.Role.Student;
import Entity.Role.Teacher;
import Entity.TitleAndPaper.Title;
import Service.Teacher.TitleAndPaperService;
import Util.DBUtil;

import java.sql.Connection;
import java.util.List;

public class TitleAndPaperServiceImp implements TitleAndPaperService {
    private Connection conn;
    private TitleDao titleDao;
    private TeacherDao teacherDao;
    private StuInfoDao stuInfoDao;

    public TitleAndPaperServiceImp() {
        teacherDao = DaoFactory.getInstance("teacherDao");
        titleDao = DaoFactory.getInstance("titleDao");
        stuInfoDao = DaoFactory.getInstance("stuInfoDao");
        conn = DBUtil.getConnByDruid();
    }

    @Override
    public MyTableData queryAllTitle(String queryKey, Integer offset, Integer limit, Integer type) {
        List<Title> titles = titleDao.queryAllTitle(queryKey, offset, limit, type, conn);
        DBUtil.closeConn(conn);
        return new MyTableData(0, "", titles.size(), titles);
    }

    @Override
    public Boolean addTitle(Title title, Integer type) {
        //根据申请的编号查询是否是老师
        String TNO = title.getNo();  // 默认的是老师
        if (type == 1) { //如果申请人是学生 则需要先查询到关联的指导老师的编号
            List<Student> students = stuInfoDao.getStuByNO(title.getNo(), conn);
            if (students.size() == 1) {
                TNO = students.get(0).getTNO();
                title.setMajorName(students.get(0).getMajorName());
                title.setCollegeName(students.get(0).getCollName());
                title.setSname(students.get(0).getName());
            } else {
                return false;
            }
        }
        List<Teacher> teacher = teacherDao.getTeacherByNO(TNO, conn);
        if (teacher.size() == 1) {
            title.setTno(teacher.get(0).getTNO());
            title.setTName(teacher.get(0).getName());
        } else {
            return false;
        }
        boolean flag = titleDao.insertTitle(title, type, conn) == 1;
        DBUtil.closeConn(conn);
        return flag;
    }

    @Override
    public Boolean checkTitle(String result, String opinion, Integer id) {
        boolean flag = titleDao.updateIsPass(result, opinion, id, conn) == 1;
        DBUtil.closeConn(conn);
        return flag;
    }

}
